<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    img {
      display: block;
      width: 100%;
      height: 300px;
      margin-bottom: 20px;
    }
  </style>
</head>

<body>
  <img data-src="./images/1.jpg" alt="">
  <img data-src="./images/2.jpg" alt="">
  <img data-src="./images/3.jpg" alt="">
  <img data-src="./images/4.jpg" alt="">
  <img data-src="./images/5.jpg" alt="">
  <img data-src="./images/6.jpg" alt="">
  <script>
    var imgs = document.querySelectorAll('img');

    function lazyLoad() {
      // 可见区域高度
      var h = window.innerHeight || document.documentElement.clientHeight;
      // 滚动条距离顶部的高度
      var s = document.documentElement.scrollTop || document.body.scrollTop;
      for (let i = 0; i < imgs.length; i++) {
        if (h + s > imgs[i].offsetTop) {
          if (!imgs[i].getAttribute("src")) {
            imgs[i].src = imgs[i].getAttribute('data-src');
          }
        }
      }
    }
    //页面载入完毕加载可是区域内的图片
    lazyLoad();
    // 节流是滚动一段时间执行一次懒加载函数
    window.onscroll = throttle(lazyLoad,500) //onscroll()在滚动条滚动的时候触发
    // 防抖是 滚动停止之后才触发懒加载函数
    // window.onscroll = debounce(lazyLoad,500) //onscroll()在滚动条滚动的时候触发
    // 节流
    function throttle(lazyLoad,delay) {
      let timer =null;
      return function() {
        if(timer) {
          console.log('wzy');
          return;
        }
        timer = setTimeout(() => {
          lazyLoad();
          console.log('sss');
          timer = null;
        }, delay);
      }
    }

    // 防抖
    function debounce(lazyLoad,delay) {
      let timer = null;
      return function() {
        if(timer) {
          clearTimeout(timer);
          timer = null;
        }
        timer = setTimeout(() => {
          lazyLoad();
        }, delay);
      }
    }


    // var num = document.getElementsByTagName('img').length;
    // var img = document.getElementsByTagName("img");
    // var n = 0; //存储图片加载到的位置，避免每次都从第一张图片开始遍历

    // function lazyload() { //监听页面滚动事件
    //   var seeHeight = document.documentElement.clientHeight; //可见区域高度
    //   var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; //滚动条距离顶部高度
    //   for (var i = n; i < num; i++) {
    //     if (img[i].offsetTop < seeHeight + scrollTop) {
    //       if (!img[i].getAttribute("src")) {
    //         img[i].src = img[i].getAttribute("data-src");
    //       }
    //       n = i + 1;
    //     }
    //   }
    // }
  </script>
</body>

</html>